/**
 * 
 */
package com.common.distributed.datasource.readwritestragy;

import java.util.List;

import com.common.distributed.datasource.spring.config.schema.CommonDatasourceSchema;

/**
 * @author liubing1
 * 均匀轮询算法
 */
public class CommonDatasourceRobin {
	
	public static CommonDatasourceSchema GetBestCommonDatasourceSchema(List<CommonDatasourceServer> commonDatasourceSchemas) {
		CommonDatasourceServer server = null;
		CommonDatasourceServer best = null;
        int total = 0;
        for(int i=0,len=commonDatasourceSchemas.size();i<len;i++){
            //当前服务器对象
        	server = commonDatasourceSchemas.get(i);
        	 //当前服务器已宕机，排除
            if(server.isDown()){
                continue;
            }
            server.currentWeight += server.effectiveWeight;
            total += server.effectiveWeight;
            
            if(server.effectiveWeight < server.weight){
                server.effectiveWeight++;
            }
            
            if(best == null || server.currentWeight>best.currentWeight){
                best = server;
            }
            
        }

        if (best == null) {
            return null;
        }
        best.currentWeight -= total;
        return best.getCommonDatasourceSchema();
    }
}	
